﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using System.Net;
using System.Xml;
using System.IO;
using System.Web;

namespace Readify.Management.Automation.GoGrid
{
    [Cmdlet("Get", "GoGridServerPassword")]
    public class GetGoGridServerPasswordCmdlet : Cmdlet
    {
        [Parameter(Mandatory = true)]
        public PSCredential Credential { get; set; }

        protected override void ProcessRecord()
        {
            string url = this.BuildUrl();

            XmlDocument document = GoGridHelper.ProcessRequest(url, this);
            XmlNodeList objectElementNodeList = document.SelectNodes("/gogrid/response/list/object[@name = 'password']");

            foreach (XmlNode objectElementNode in objectElementNodeList)
            {
                GoGridServerPassword password = GoGridServerPassword.CreateFromXmlNode(objectElementNode);
                this.WriteObject(password);
            }
        }

        private string BuildUrl()
        {
            string url = this.BuildBasicUrl();
            return url;
        }

        private string BuildBasicUrl()
        {
            string urlFormat = "https://api.gogrid.com/api/support/password/list?api_key={0}&sig={1}&v=1.0&format=xml";

            NetworkCredential credential = this.Credential.GetNetworkCredential();
            string apiKey = credential.UserName;
            string secret = credential.Password;

            string signature = GoGridHelper.GenerateRequestSignature(apiKey, secret);

            string basicUrl = string.Format(urlFormat, apiKey, signature);
            return basicUrl;
        }
    }
}
